import logging
import subprocess
from flask import Flask, request
from settings import BLOG_REBUILD_SCRIPT, LOG_FILE

# log config
handler = logging.FileHandler(LOG_FILE)
formatter= logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)

app = Flask(__name__)
app.logger.addHandler(handler)

# 在shell中执行命令
def run_in_shell(command):
    app.logger.info("command={}".format(command))
    ret = subprocess.run(command, shell=True, encoding="utf-8", timeout=10000)
    if ret.returncode == 0:
        app.logger.info("stdout:{}".format(ret.stdout))
        print("stdout:", ret.stdout)
    else:
        app.logger.info("stderr:{}".format(ret.stderr))
        print("stderr:", ret.stderr)


@app.route('/webhook', methods=['GET', 'POST'])
def hook():
    data = request.get_json()
    print(data)
    app.logger.info("hook={}".format(data))

    if(data):
        repo = data['password']

        app.logger.info("repo={}".format(repo))
        if(repo == 'mehameha'):
            run_in_shell(BLOG_REBUILD_SCRIPT)

    return {
        'code': '0',
        'msg': 'ok'
    }